package fun.mashuai.generator.util;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * @author 马帅
 * @version 1.0
 * @className PathUtil.java
 * @description 项目路径工具
 * @date 2020/4/14 17:23
 */
public class PathUtil {

    public final static String CLASS_PATH_NAME = "classpath:";
    public final static String FILE_START_NAME = "file:/";


    /**
     * 获取项目不同模式下的根路径
     */
    public static String getProjectPath(){

        String filePath = PathUtil.class.getResource("").getPath();
        String projectPath = PathUtil.class.getClassLoader().getResource("").getPath();
        String path = "";

        try {
            File file = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile();

            // 开发模式下根路径
            if(!filePath.startsWith(FILE_START_NAME)){
                path =  file.getPath().replaceAll("\\\\","/");

                // tomcat部署服务器模式下根路径
            }else if(!projectPath.startsWith(FILE_START_NAME)){
                path =  file.getPath().replaceAll("\\\\","/");

                // jar包启动模式下根路径
            }else {
                path =  file.getPath().replaceAll("\\\\","/").replace("file:", "");
            }

        } catch (
                FileNotFoundException e) {
            e.printStackTrace();
        }

        return path;

    }

    public static void main(String[] args) {
        System.out.println(getProjectPath());
    }

}
